#include "thread_handle.h"
#include "QiSerial/qiserialport.h"
#include "QiSerial/qiserialportbuffer.h"

uint8_t thread_handle::_exit = 0;
struct check_rang_arg thread_handle::_param;

thread_handle::thread_handle(struct interface_data *_data, QObject *parent) : QObject(parent)
{
    _storage = new cJSONstorage("ipmb.txt");
    _storage->opencJSON();
    _interface_data = _data;
    _param_flag = 0;
}

void thread_handle::doWork(const QString COM)
{
    qDebug() << "cpu::doWork into ";
    QString port;
    QString str;
    _port = new QiSerialPort();
    //_port = new QiSerialPortBuffer();
    qDebug() << "Worker Run Thread : " << QThread::currentThreadId();
    qDebug() << QDateTime::currentDateTime().toString("yyyy.MM.dd hh:mm:ss.zzz ddd") ;
    //interface = new interface_ipmc(this);
    interface = new interface_sensor(*_port);
    connect(interface, SIGNAL(sig_progress_update(const QString &, int)), this, SLOT(slots_progress_update(const QString &, int)));
    uint time_now =QDateTime::currentDateTime().toTime_t();
    uint time_start =QDateTime::currentDateTime().toTime_t();
    uint timeout =time_start+30; // 30s 建立连接时间
    port = COM;

    _stop = 0;
    while((0==_exit) && (0==_stop))
    {
        QThread::msleep(10);
        // 30s timeout
        time_now =QDateTime::currentDateTime().toTime_t();
        if(timeout<time_now)
        {
             break;
        }
#if 0
        if (!port.compare("COM") && !port.compare("APM") && !port.compare("ACM") && !port.compare("usb"))
            continue;
#endif
        str = " Watting connect " + port + "sec:" + QString::number(time_now-time_start);
        emit sig_progress_update(str, QiMSGSync::SingalCode::MSG);
        if(0!=_port->OpenPortDefault(port)) continue;
        //connect(_port, &user_port::errorOccurred, _port, &user_port::errorOccurred_slots);
        // 同步,获取信息
        if(0!=interface->identify())
        {
            emit sig_progress_update("SYNC FAIL!", QiMSGSync::SingalCode::MSG);
        }
        else
        {
//            _param.accel_min = interface->__readParam(QiMSGSync::Info::PARAM1);
//            _param.accel_max = interface->__readParam(QiMSGSync::Info::PARAM2);
//            _param.mbar_min = interface->__readParam(QiMSGSync::Info::PARAM3);
//            _param.mbar_max = interface->__readParam(QiMSGSync::Info::PARAM4);
//            _param.temp_min = interface->__readParam(QiMSGSync::Info::PARAM5);
//            _param.temp_max = interface->__readParam(QiMSGSync::Info::PARAM6);
//            _param.temp_diff = interface->__readParam(QiMSGSync::Info::PARAM7);
//            emit sig_progress_update("Param", QiMSGSync::SingalCode::PARAM);
//            interface->__stream();
            loop();
        }
        if(0!=_port->stop()) break;
        interface->__reboot();
        //QThread::msleep(500);
        //disconnect(_port, &user_port::errorOccurred, _port, &user_port::errorOccurred_slots);
        _port->close();
    }
    emit sig_progress_update(COM, QiMSGSync::SingalCode::DOWN);
    delete interface;
    delete _port;
    uint time_end =QDateTime::currentDateTime().toTime_t();
    uint _time = time_end-time_start;
    emit sig_progress_update(" Time:"+QString::number(_time)+" s", QiMSGSync::SingalCode::TIME);
    if(1==_exit) exit(0);
}

void thread_handle::loop()
{
//    uint32_t count=0;
    int ret = -1;
    uint8_t buffer[128];
    uint8_t name[16];
    uint8_t _lenght=0;
    uint8_t i=0;
    _search_flag = 1;
    interface->__stream();
    // 读取数据
    while((0==_exit) && (0==_stop))
    {
//        qDebug() << "count:" << count;
//        QThread::msleep(1000);
//        count++;
        //interface->__stream();
        if(0!=_port->stop())
        {
            _stop=1;
            emit sig_progress_update("通讯错误", QiMSGSync::SingalCode::MSG);
        }
//        if(1==_param_flag)
//        {
//            qDebug("写入参数，获取同步信号");
//            for(i=0; i<50; i++)
//            {
//                if(0==interface->__sync()) break;
//            }
//            qDebug("开始写入 %d", i);
//            _param_flag=0;
//            interface->__writeParam(QiMSGSync::Info::PARAM1, _param.accel_min);
//            interface->__writeParam(QiMSGSync::Info::PARAM2, _param.accel_max);
//            interface->__writeParam(QiMSGSync::Info::PARAM3, _param.mbar_min);
//            interface->__writeParam(QiMSGSync::Info::PARAM4, _param.mbar_max);
//            interface->__writeParam(QiMSGSync::Info::PARAM5, _param.temp_min);
//            interface->__writeParam(QiMSGSync::Info::PARAM6, _param.temp_max);
//            interface->__writeParam(QiMSGSync::Info::PARAM7, _param.temp_diff);
//            emit sig_progress_update("参数写入完成", QiMSGSync::SingalCode::MSG);
//            QThread::msleep(300);
//            _param.accel_min = interface->__readParam(QiMSGSync::Info::PARAM1);
//            _param.accel_max = interface->__readParam(QiMSGSync::Info::PARAM2);
//            _param.mbar_min = interface->__readParam(QiMSGSync::Info::PARAM3);
//            _param.mbar_max = interface->__readParam(QiMSGSync::Info::PARAM4);
//            _param.temp_min = interface->__readParam(QiMSGSync::Info::PARAM5);
//            _param.temp_max = interface->__readParam(QiMSGSync::Info::PARAM6);
//            _param.temp_diff = interface->__readParam(QiMSGSync::Info::PARAM7);
//            emit sig_progress_update("Param", QiMSGSync::SingalCode::PARAM);
//            interface->__stream();
//        }
        // recv
        memset(buffer, 0, sizeof(buffer));
        memset(name, 0, sizeof(name));
        ret = interface->msg_send2_pc(interface_sensor::IPMC::MSG2PC, QiMSGSync::OK, QiMSGSync::EOC, \
                                name, buffer, sizeof (buffer));
        _lenght = static_cast<uint8_t>(ret);
        if(ret>0)
        {
            //QString SPI0 = "SPI0";
            //qDebug("name: %s _lenght:%d", name, _lenght);
            // decode
            struct interface_data _data;
            int index=0;
            interface->float_from_buf(&buffer[4*0], &_data._accel_x);
            interface->float_from_buf(&buffer[4*1], &_data._accel_y);
            interface->float_from_buf(&buffer[4*2], &_data._accel_z);
            interface->float_from_buf(&buffer[4*3], &_data._last_temperature);
            interface->float_from_buf(&buffer[4*4], &_data._gyro_x);
            interface->float_from_buf(&buffer[4*5], &_data._gyro_y);
            interface->float_from_buf(&buffer[4*6], &_data._gyro_z);
            interface->float_from_buf(&buffer[4*7], &_data.pressure);
            interface->float_from_buf(&buffer[4*8], &_data.temperature);
            _data.acc_whoami = buffer[4*9];
            index = search_index((const char *)name);
            //qDebug("name: %s index:%d _lenght:%d", name, index, _lenght);
            if(index<0)
            {
                continue;
            }
            //if(0==index) qDebug("mpu6000[0x%02X]: acc[ %2.03f, %2.03f, %2.03f T:%2.1f] gyro[ %2.03f, %2.03f, %2.03f] ", _data.acc_whoami, _data._accel_x, _data._accel_y, _data._accel_z, _data._last_temperature, _data._gyro_x, _data._gyro_y, _data._gyro_z);
            memcpy(&_interface_data[index], &_data, sizeof(struct interface_data));
            emit sig_progress_update(QString::fromLocal8Bit((const char*)name), QiMSGSync::SingalCode::REPO);
//            ret = _ipmc_protocol.decode_send_cpu(&pack_ipmc, _ipmc_protocol.get_ipmb_addr(), buffer, _lenght);
//            //qDebug("decode_send_cpu: %d", ret);
//            if(0==ret)
//            {
//                ret = _ipmc_protocol.decode_item(&pack_ipmc);
//                if(0==ret)
//                {
//                    // 上报数据
//                    emit sig_progress_update(QString::number(pack_ipmc.rsSA), QiMSGSync::SingalCode::REPO);
//                    emit sig_progress_update("接收到数据 ADDR:0x"+QString("%1").arg(pack_ipmc.rsSA, 2, 16, QLatin1Char('0')) + \
//                                             " NetFn:0x"+QString("%1").arg(pack_ipmc.NetFn, 2, 16, QLatin1Char('0')), QiMSGSync::SingalCode::MSG);
//                }
//                else
//                {
//                    emit sig_progress_update("接收到编码错误数据", QiMSGSync::SingalCode::MSG);
//                }
//            }
        }
    }
}

int thread_handle::search_index(const char *name)
{
    int index=-1;
    //if(('S'!=name[0]) || ('P'!=name[1]) || ('I'==name[2])) return -1;
    if('S'!=name[0]) return -1;
    if('P'!=name[1]) return -2;
    if('I'!=name[2]) return -3;
    index = name[3]-'0';
    if(index>=8) return -4;
    return index;
}
